package com.msgc.servlet;
 
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
 
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* Type: WebSocketServer
* Description: WebSocketServer,实现服务器客户端平等交流，
* 		达到服务器可以主动向客户端发生消息
* @author LYM
* @date Dec 18, 2018
 */
//@ServerEndpoint("/websocket/{user}")
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);
	
    /** 弱一致性，放的是WebSocketServer而非session是为了复用自身的方法 */
    private static transient volatile Set<WebSocketServer> webSocketSet = ConcurrentHashMap.newKeySet();
 
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
 
    /**
     * 群发消息
     * @param message 消息
     */
    public static void sendInfo(String message) {
    	LOGGER.info("webSocket-sendInfo群发消息：" + message);
        for (WebSocketServer item : webSocketSet) {
            item.sendMessage(message);
        }
    }
 
    /**
     * 获取连接数
     * @return 连接数
     */
    public static int getOnlineCount() {
        return webSocketSet.size();
    }

    /* *********************以下为非static方法************************** */

    /**
     * 向客户端发送消息
     * @param message 要向客户端发送的消息
     */
    public boolean sendMessage(String message) {
        try {
			this.session.getBasicRemote().sendText(message);
			return true;
		} catch (IOException error) {
			LOGGER.error("webSocket-sendMessage发生错误:" + error.getClass() + error.getMessage());
			return false;
		}
    }
    /**
     * 连接建立成功: 加入缓存
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        sendMessage("连接成功");
    }
 
    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
    	LOGGER.info("来自客户端(" + session.getId() + ")的消息:" + message);
    	sendMessage("Hello, nice to hear you! There are " + webSocketSet.size() + " users like you in total here!");
    }

    /**
     * 连接关闭: 移除缓存
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
    }

	/**
	 * 发生错误时候回调函数
	 * @param session   哪个连接
	 * @param error     什么错误
	 */
    @OnError
    public void onError(Session session, Throwable error) {
        LOGGER.error("webSocket发生错误:" + error.getClass() + error.getMessage());
    }
 
    @Override
    public int hashCode() {
    	return super.hashCode();
    }
    
    @Override
    public boolean equals(Object obj) {
    	return super.equals(obj);
    }
}
